package tech.yangzhijie.basic.knowledge.mianshi;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

public class Test08CompareAndSwapABA {

    public static void main(String[] args) {
        /*
        CompareAndSwapABADemo02 demo = new CompareAndSwapABADemo02();
        CountDownLatch countDownLatch = new CountDownLatch(100000);

        for (int i = 0; i < 100000; i++) {
            final int num = i;
            new Thread(()->{
                if(num == 1000 || num == 5000){
                    demo.getValue().getAndDecrement();
                    demo.getValue().getAndIncrement();
                }
                demo.getValue().getAndIncrement();
                countDownLatch.countDown();
            }).start();
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("最终结果: " + demo.getValue() + "\t最终版本号: " + demo.getVersion());
        */
        ABA();
    }

    public static void ABA(){
        CompareAndSwapABADemo02 demo = new CompareAndSwapABADemo02();
        CountDownLatch countDownLatch = new CountDownLatch(10000);
        AtomicStampedReference<AtomicInteger> stampedReference = demo.getStampedReference();
        long start = System.currentTimeMillis();
        for (int i = 1; i <= 10000; i++) {
            final int num = i;
            new Thread(()->{
                /*if(stampedReference.compareAndSet(demo.getValue(),demo.getValue(),stampedReference.getStamp(),stampedReference.getStamp()+1)){
                    demo.getValue().getAndIncrement();
                }else {
                    System.out.println(Thread.currentThread().getName() + " 当前版本号：" + stampedReference.getStamp());
                }*/
                demo.getValue().getAndAdd(num);
                countDownLatch.countDown();
            }).start();
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("总时间: " + (end - start) + " 最终结果: " + stampedReference.getReference().get() + "\t最终版本号: " + stampedReference.getStamp());
    }
}

class CompareAndSwapABADemo02 {

    private AtomicInteger value = new AtomicInteger();
    private AtomicStampedReference<AtomicInteger> stampedReference = new AtomicStampedReference<>(value,0);

    public AtomicInteger getValue() {
        return value;
    }
    public AtomicStampedReference<AtomicInteger> getStampedReference() {
        return stampedReference;
    }
}
